package com.sendi.mobilework.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sendi.mobilework.R;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/3/22.
 */

public class RefreshListView extends ListView implements AdapterView.OnItemClickListener {
    //状态
    private static final int STATE_PULL_REFRESH = 0;//下拉刷新
    private static final int STATE_REFRESHING = 1;//正在刷新
    private static final int STATE_RELASE_REFRESH = 2;//松开刷新

    //默认状态下拉刷新
    private int mCurrentState = 0;

    //头布局相应的参数
    private int headerHeight;

    private int startY = -1;

    //动画
    private RotateAnimation raUp;
    private RotateAnimation raDown;

    private ImageView imageView;
    private ProgressBar progressBar;
    private TextView tv_state;
    private TextView tv_time;

    private View mHeaderView;//头布局

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initHeaderView();
    }

    public RefreshListView(Context context) {
        super(context);
        initHeaderView();
    }

    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initHeaderView();
    }

    /**
     * 初始化头布局
     */
    private void initHeaderView() {
        mHeaderView = View.inflate(getContext(), R.layout.listview_header, null);
        imageView = (ImageView) mHeaderView.findViewById(R.id.iv_refresh);
        progressBar = (ProgressBar) mHeaderView.findViewById(R.id.pb_refresh);
        tv_state = (TextView) mHeaderView.findViewById(R.id.tv_refresh);
        tv_time = (TextView) mHeaderView.findViewById(R.id.tv_time);

        mHeaderView.measure(0, 0);
        headerHeight = mHeaderView.getMeasuredHeight();
        mHeaderView.setPadding(0, -headerHeight, 0, 0);//隐藏头布局
        //添加头布局
        this.addHeaderView(mHeaderView);
        refreshAnimation();//初始化动画效果
    }

    /**
     * 监听改变刷新状态
     *
     * @param ev
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN://手指按下
                startY = (int) ev.getRawY();//按下时获得的Y坐标
                break;
            case MotionEvent.ACTION_MOVE://手指滑动
                if (startY == -1) {
                    startY = (int) ev.getRawY();
                }
                int endY = (int) ev.getRawY();//移动时获得的Y坐标
                int dy = endY - startY;
                if (mCurrentState == STATE_REFRESHING) {
                    break;//当正在刷新时不做处理
                }
                if (dy > 0 && getFirstVisiblePosition() == 0) {//此时才能拉出头布局
                    mHeaderView.setPadding(0, dy - headerHeight, 0, 0);//更新头布局的显示高度
                    if (dy > headerHeight && mCurrentState != STATE_RELASE_REFRESH) {
                        //把状态改为松开刷新
                        mCurrentState = STATE_RELASE_REFRESH;
                        refreshState();
                    } else if (dy < headerHeight && mCurrentState != STATE_PULL_REFRESH) {
                        //把状态改为下拉刷新
                        mCurrentState = STATE_PULL_REFRESH;
                        refreshState();
                    }

                    return true;
                }
                break;
            case MotionEvent.ACTION_UP://手指抬
                startY = -1;//重置
                if (mCurrentState == STATE_PULL_REFRESH) {//收回
                    mHeaderView.setPadding(0, -headerHeight, 0, 0);
                } else if (mCurrentState == STATE_RELASE_REFRESH) {//转变正在刷新
                    mCurrentState = STATE_REFRESHING;
                    mHeaderView.setPadding(0, 0, 0, 0);
                    refreshState();
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    public void refreshState() {
        switch (mCurrentState) {
            case STATE_PULL_REFRESH:
                tv_state.setText("下拉刷新...");
                imageView.setVisibility(View.VISIBLE);//箭头显示
                progressBar.setVisibility(View.GONE);//刷新环消失
                imageView.startAnimation(raDown);
//                tv_time.setText("上次刷新时间："+getCurrentTime());
                break;
            case STATE_REFRESHING:
                tv_state.setText("正在刷新...");
                imageView.setVisibility(View.GONE);
                imageView.clearAnimation();//清除动画
                progressBar.setVisibility(View.VISIBLE);
                if (mListener != null) {
                    mListener.onRefresh();//执行刷新
                }
                break;
            case STATE_RELASE_REFRESH:
                tv_state.setText("松开刷新...");
                imageView.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.GONE);
                imageView.startAnimation(raUp);
                break;
        }
    }

    /**
     * 刷新完成,收回头布局
     */
    public void refreshComplete(boolean success) {
        mCurrentState = STATE_PULL_REFRESH;
        mHeaderView.setPadding(0, -headerHeight, 0, 0);
        tv_state.setText("下拉刷新");
        imageView.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.INVISIBLE);

        if (success) {
            tv_time.setText("上次刷新时间：" + getCurrentTime());
        }
    }


    /**
     * 获取当前时间
     */
    public String getCurrentTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());

    }

    /**
     * 动画效果
     */
    public void refreshAnimation() {
        //向上的动画
        raUp = new RotateAnimation(0, -180,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        raUp.setDuration(300);
        raUp.setFillAfter(true);

        //向下的动画
        raDown = new RotateAnimation(-180, 0,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        raUp.setDuration(300);
        raUp.setFillAfter(true);
    }

    OnRefreshListener mListener;

    public void setOnRefreshListener(OnRefreshListener listener) {
        mListener = listener;
    }

    OnItemClickListener mItemClickListener;

    @Override
    public void setOnItemClickListener(OnItemClickListener listener) {
        //调用自定义的onItemClick方法
        mItemClickListener = listener;
        super.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mItemClickListener != null) {
            //减去头布局数量
            mItemClickListener.onItemClick(parent, view, position - this.getHeaderViewsCount(), id);
        }
    }

    /**
     * 刷新接口
     */
    public interface OnRefreshListener {
        void onRefresh();
    }
}
